import os, time
from operator import itemgetter
from Tkinter import *

class main():
    def __init__(self,parent,root):
        
        self.root = root
        self.root.title('View All Consignors')
        self.parent = parent
        self.dh = parent.dh
        cons_nums = []
        self.keyword = StringVar()

        self.status = StringVar()
        self.status.set('Enter consignor by name or number and click Search to get started')
        
        kwLabel = Label(self.root,text= 'Keyword : ').grid(row=0,column=0,sticky=W)
        findByKw = Button(self.root, text='Search',command=self.searchByKw, width=10).grid(row=0,column=1)
        self.resultsBox = Listbox(self.root,width=80,height=30)
        self.resultsBox.grid(row=1,column=0,columnspan=3)
        self.resultsBox.bind('<Double-Button-1>',self.openEditCons)
        self.searchByKw()
        
        doneButton = Button(self.root,text=' Done ', command=self.finalize, width=10).grid(row=2,column=2,sticky=E)

            
    def searchByKw(self):
        insTexts = []
        for key in self.dh.cons_dict.keys():
            cons = self.dh.cons_dict[key]
            insTexts.append([cons.number,cons.last_name, cons.first_name, cons.phone_number, cons.email_address])
                             
        insTexts = sorted(insTexts, key = itemgetter(1))
        for ins in insTexts:
            insText = '%s  %s, %s  %s  %s' % (ins[0],ins[1],ins[2],ins[3],ins[4])                    

            self.resultsBox.insert(END, insText)

                    
   
    def openEditCons(self,event=None):
        import add_consignor
        anchor=self.resultsBox.curselection()
        cons_data = self.resultsBox.get(anchor)
        cons_num = cons_data.split()[0]
        top = Toplevel()
        editor = add_consignor.main(self.parent,top)
        editor.num.set(int(cons_num))
        editor.readConsignorNum()    
               
    
    def finalize(self):
        self.root.destroy()
            
        

def start(parent,root):
        
    ins = main(parent,root)
